﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Renci.iRods.Linq.Common;
using Renci.iRods.Linq.Translators;
using System.Reflection;
using System.Data.SqlClient;

namespace Renci.iRods.Linq
{
    public class PgSqlLanguage : QueryLanguage
    {
        SqlCommandBuilder cb = new SqlCommandBuilder();
        TSqlTypeSystem typeSystem = new TSqlTypeSystem();

        public override QueryTypeSystem TypeSystem
        {
            get { return this.typeSystem; }
        }

        public override string Quote(string name)
        {
            return cb.QuoteIdentifier(name);
        }

        public override Expression Translate(Expression expression)
        {
            // fix up any order-by's
            expression = OrderByRewriter.Rewrite(expression);

            expression = base.Translate(expression);

            // convert skip/take info into RowNumber pattern
            expression = SkipRewriter.Rewrite(expression);

            // fix up any order-by's we may have changed
            expression = OrderByRewriter.Rewrite(expression);

            return expression;
        }

        public override IRodsQuery Format(Expression expression)
        {
            //return "Irods query based on expression";
            return TSqlFormatter.Format(expression);
        }

        public override Expression GetGeneratedIdExpression(MemberInfo member)
        {
            return new FunctionExpression(TypeHelper.GetMemberType(member), "SCOPE_IDENTITY()", null);
        }
    }

}
